package com.ztao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.model.common.admin.dto.AdminLoginDto;
import com.heima.model.common.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.ztao.mapper.AdminUserMapper;
import com.ztao.service.AdUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
    public class AdUserServiceImpl implements AdUserService {
    @Resource
    private AdminUserMapper userMapper ;
    @Override
    public ResponseResult login(AdminLoginDto dto) {
        if(StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名不能为空");
        }else {
            QueryWrapper<AdUser> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(AdUser::getName,dto.getName());
            AdUser adUser = this.userMapper.selectOne(queryWrapper);
            if(adUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名不存在");
            }
            String pwd = adUser.getSalt();
            String pwd1 = dto.getPassword();
            pwd1= DigestUtils.md5DigestAsHex((pwd1+pwd).getBytes());
            if(!pwd1.equals(adUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            Map<String,Object> map=new HashMap<>();
            map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
            adUser.setSalt(null);
            adUser.setPassword(null);
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        }
    }


}
